from django.shortcuts import render
from django.core.cache import cache
from django.http import StreamingHttpResponse, HttpResponseNotFound, HttpResponse
from .models import XhsNote
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import XhsNoteSerializer
from django.core.paginator import Paginator, EmptyPage
import requests

class VideoListView(APIView):
    """
    视频列表视图
    """
    def get(self, request):
        note_id = request.GET.get('note_id')
        page = request.GET.get('page', 1)
        page_size = request.GET.get('page_size', 10)

        if not note_id:
            return Response({'error': '缺少 note_id 参数'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 从缓存中尝试获取数据
            # cache_key = f'videos_{note_id}_page_{page}_size_{page_size}'
            # cached_data = cache.get(cache_key)
            cached_data = None
            if cached_data:
                return Response(cached_data, status=status.HTTP_200_OK)

            # 查询特定笔记的所有视频
            videos = XhsNote.objects.filter(id=note_id)
            paginator = Paginator(videos, page_size)
            try:
                paginated_videos = paginator.page(page)
            except EmptyPage:
                return Response({'error': '请求的页面不存在'}, status=status.HTTP_404_NOT_FOUND)

            serializer = XhsNoteSerializer(paginated_videos, many=True)
            data = {
                'results': serializer.data,
                'total': paginator.count,
                'current_page': paginated_videos.number
            }

            # 将结果缓存5分钟
            # cache.set(cache_key, data, timeout=300)

            return Response(data, status=status.HTTP_200_OK)

        except XhsNote.DoesNotExist:
            return Response({'error': '笔记不存在'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class VideoStreamView(APIView):
    """
    视频流式传输视图
    """
    def get(self, request):
        note_id = request.GET.get('note_id')
        if not note_id:
            return HttpResponseNotFound('缺少 note_id 参数')

        try:
            # 从数据库获取笔记数据
            note = XhsNote.objects.get(id=note_id)
            video_url = note.video_url
            print(video_url)
            if not video_url:
                return HttpResponseNotFound('未找到视频链接')

            # 发送GET请求获取视频数据
            response = requests.get(video_url, stream=True, timeout=10)
            if response.status_code != 200:
                return HttpResponseNotFound('视频未找到或不可访问')

            # 获取视频大小和类型
            content_length = response.headers.get('content-length')
            content_type = response.headers.get('content-type', 'video/mp4')

            # 创建流式响应
            streaming_response = StreamingHttpResponse(
                response.iter_content(chunk_size=8192),
                content_type=content_type
            )

            # 设置响应头
            if content_length:
                streaming_response['Content-Length'] = content_length
            streaming_response['Accept-Ranges'] = 'bytes'
            streaming_response['Content-Disposition'] = f'inline; filename="video_{note_id}.mp4"'

            return streaming_response

        except XhsNote.DoesNotExist:
            return HttpResponseNotFound('未找到对应的笔记')
        except requests.RequestException as e:
            return HttpResponseNotFound(f'获取视频时出错: {str(e)}')